import { getUser, getUserSearchList} from '@/services';
import { User,SearchUserList } from '@/types';
import { Effect, Reducer } from 'umi';

export interface UserModelState {
    userList: User[];
    SearchUserList:SearchUserList[]
}

export interface userModelType {
  namespace: 'sysUser';
  state: UserModelState;
  effects: {
    getUser: Effect;
    getUserSearchList: Effect;
  };
  reducers: {
    save: Reducer<UserModelState>;
  };
}

const ArticleModel: userModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'sysUser',

  // 数据模型状态，相当于vuex的state
  state: {
    userList: [],
    SearchUserList:[]
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    // 总数据
    *getUser({ payload }, { call, put }) {
      let result = yield call(getUser, payload);
      if (result.records) {
        yield put({
          type: 'save',
          payload: {
            userList: result.records,
          },
        });
      }
    },
    *getUserSearchList({ payload }, { call, put }) {
      const result = yield call(getUserSearchList,payload);
      localStorage.setItem('UserSearchList',JSON.stringify(result.records));
      if (result) {
          yield put({
              type: "save",
              payload: {
                SearchUserList: result.records,                       
              }
          })
      }
    },
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default ArticleModel;
